package cn.dengta.webapp.trade.entity.meta;

import java.io.Serializable;

import cn.dengta.webapp.trade.entity.meta.MetaConfig.MetaRuleConfig;
import cn.dengta.webapp.user.model.PlanetExploreType;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter;
import lombok.Setter;
import me.codeplayer.util.Assert;
import me.codeplayer.util.X;

/**
 * 星球探险的规则配置对象
 */
@Getter
@Setter
public class PlanetExploreRule implements MetaRuleConfig {

	/** 限制购买次数 */
	private Integer buyMax;
	/** 单次价格 */
	private Integer price;
	/** 星球探险配置 */
	public PlanetExploreEntry[] entries;

	@Override
	public void validate() {
		final PlanetExploreEntry[] entries = this.entries;
		Assert.isTrue(X.size(entries) > 0, "星球探险配置不能为空！");
		Assert.isTrue(buyMax > 0, "每个星球限购必须大于0！");
		Assert.isTrue(X.size(entries) == X.size(PlanetExploreType.CACHE), "尚不支持自定义设置星球");
		for (PlanetExploreEntry entry : entries) {
			entry.validate();
		}
	}

	@Override
	public void init(MetaRuleConfig config) {
		PlanetExploreRule rule = (PlanetExploreRule) config;
		this.buyMax = rule.buyMax;
		this.price = rule.price;
		this.entries = rule.entries;
	}

	@JSONField(serialize = false)
	public PlanetExploreEntry getEntry(Integer type, boolean defaultValue) {
		final PlanetExploreEntry[] entries = this.entries;
		PlanetExploreEntry entry;
		for (int i = entries.length - 1; i >= 0; i--) {
			entry = entries[i];
			if (entry.getType().equals(type)) {
				return entry;
			}
		}
		return defaultValue ? entries[0] : null;
	}

	/**
	 * 星球探险规则实体
	 */
	@Setter
	@Getter
	public static class PlanetExploreEntry implements Serializable {

		/** 类型 */
		protected Integer type;
		/** 奖励钻石 */
		protected Integer awardCoin;

		public PlanetExploreEntry() {
		}

		public PlanetExploreEntry(Integer type, Integer awardCoin) {
			this.type = type;
			this.awardCoin = awardCoin;
		}

		public void validate() {
			PlanetExploreType type = PlanetExploreType.of(this.type);
			Assert.isTrue(type != null, "请核实星球设置是否正确！");
			Assert.isTrue(awardCoin > 0, "奖励钻石必须大于0！");
		}

	}

}
